// pages/order-list/order-list.js
const app = getApp();

Page({
  data: {
    status: '',
    orderList: []
  },

  onLoad(options) {
    if (options.status) {
      this.setData({ status: options.status });
    }
    this.loadOrderList();
  },

  onShow() {
    this.loadOrderList();
  },

  loadOrderList() {
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo) {
      return;
    }

    app.showLoading();
    const params = {
      userId: userInfo.id,
      page: 1,
      size: 100
    };

    if (this.data.status) {
      params.status = this.data.status;
    }

    app.request({
      url: '/order/list',
      method: 'GET',
      data: params
    }).then(res => {
      if (res.success) {
        const orders = (res.data.records || []).map(order => ({
          ...order,
          details: (order.details || []).map(detail => ({
            ...detail,
            // 后端返回的是productImage（单数），直接使用
            productImage: detail.productImage || 'https://img1.baidu.com/it/u=2531584226,2194794184&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500'
          }))
        }));
        this.setData({ orderList: orders });
      }
    }).catch(err => {
      app.showToast('加载失败');
      console.error(err);
    }).finally(() => {
      app.hideLoading();
    });
  },

  filterByStatus(e) {
    const status = e.currentTarget.dataset.status;
    this.setData({ status: status });
    this.loadOrderList();
  },

  // 取消订单
  cancelOrder(e) {
    const id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '确定要取消该订单吗？',
      success: (res) => {
        if (res.confirm) {
          const userInfo = wx.getStorageSync('userInfo');
          app.showLoading();
          app.request({
            url: '/order/cancel',
            method: 'POST',
            data: {
              orderId: id,
              userId: userInfo.id
            }
          }).then(res => {
            if (res.success) {
              app.showToast('订单已取消', 'success');
              this.loadOrderList();
            } else {
              app.showToast(res.message || '取消失败');
            }
          }).catch(err => {
            app.showToast('取消失败，请稍后重试');
            console.error(err);
          }).finally(() => {
            app.hideLoading();
          });
        }
      }
    });
  },

  // 支付订单
  payOrder(e) {
    const id = e.currentTarget.dataset.id;
    const order = this.data.orderList.find(o => o.id === id);
    
    wx.showModal({
      title: '确认支付',
      content: `订单金额：¥${order.totalAmount}`,
      confirmText: '确认支付',
      success: (res) => {
        if (res.confirm) {
          // 实际项目中需要调用微信支付SDK
          // wx.requestPayment({ ... })
          // 这里简化处理，直接模拟支付成功
          this.processPayment(id);
        }
      }
    });
  },

  // 处理支付（简化版，实际需要接入微信支付）
  processPayment(orderId) {
    app.showLoading('支付中...');
    
    // 模拟支付延迟
    setTimeout(() => {
      app.hideLoading();
      wx.showToast({
        title: '支付成功',
        icon: 'success'
      });
      // 刷新订单列表
      this.loadOrderList();
    }, 1000);
    
    // 注意：实际项目中需要调用后端支付接口，这里仅作演示
    // app.request({
    //   url: '/order/pay',
    //   method: 'POST',
    //   data: { orderId: orderId }
    // }).then(res => {
    //   if (res.success) {
    //     wx.showToast({ title: '支付成功', icon: 'success' });
    //     this.loadOrderList();
    //   } else {
    //     app.showToast(res.message || '支付失败');
    //   }
    // }).catch(err => {
    //   app.showToast('支付失败');
    // }).finally(() => {
    //   app.hideLoading();
    // });
  },

  // 确认收货
  confirmReceipt(e) {
    const id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '确认收货后订单将完成',
      success: (res) => {
        if (res.confirm) {
          const userInfo = wx.getStorageSync('userInfo');
          app.showLoading();
          app.request({
            url: '/order/confirm',
            method: 'POST',
            data: {
              orderId: id,
              userId: userInfo.id
            }
          }).then(res => {
            if (res.success) {
              app.showToast('确认收货成功', 'success');
              this.loadOrderList();
            } else {
              app.showToast(res.message || '确认收货失败');
            }
          }).catch(err => {
            app.showToast('确认收货失败，请稍后重试');
            console.error(err);
          }).finally(() => {
            app.hideLoading();
          });
        }
      }
    });
  },

  // 评价订单
  reviewOrder(e) {
    const order = e.currentTarget.dataset.order;
    // 跳转到评价页面，传递订单信息
    wx.navigateTo({
      url: `/pages/review-edit/review-edit?orderId=${order.id}&products=${JSON.stringify(order.details)}`
    });
  },

  // 查看详情
  viewDetail(e) {
    const id = e.currentTarget.dataset.id;
    const order = this.data.orderList.find(o => o.id === id);
    
    if (!order) return;
    
    // 构建详情信息
    let detailText = `订单编号：${order.orderNo}\n`;
    detailText += `订单状态：${order.status}\n`;
    detailText += `订单金额：¥${order.totalAmount}\n\n`;
    detailText += `收货信息：\n`;
    detailText += `${order.receiverName} ${order.receiverPhone}\n`;
    detailText += `${order.receiverAddress}\n\n`;
    detailText += `商品清单：\n`;
    
    order.details.forEach((item, index) => {
      detailText += `${index + 1}. ${item.productName}\n`;
      detailText += `   ¥${item.price} × ${item.quantity} = ¥${(item.price * item.quantity).toFixed(2)}\n`;
    });
    
    wx.showModal({
      title: '订单详情',
      content: detailText,
      showCancel: false,
      confirmText: '知道了'
    });
  }
});


